package 笔试.VIVO;

import java.util.Arrays;

public class 给粉丝分礼物 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param prices int整型一维数组 礼物的价格
     * @param k      int整型 粉丝人数
     * @return bool布尔型
     */
    public boolean canEqualDistribution(int[] prices, int k) {
        int sum = 0;
        for (int price : prices) {
            sum += price;
        }
        if (sum % k != 0) return false;
        int split = sum / k;
        System.out.println(split);
        Arrays.sort(prices);
        int len = prices.length;
        if (prices[len - 1] > split || k > len) return false;
        int left = 0;
        int right = len - 1;
        while (prices[left] == split) {
            left++;
            k--;
        }
        while (prices[right] == split) {
            right--;
            k--;
        }
        System.out.println(Arrays.toString(prices));
        int temp = 0;
        while (left < right) {
            if (prices[left] + prices[right] == split) {
                temp = 0;
                left++;
                right--;
                k--;
            } else {
                if (temp + prices[left] + prices[right] == split) {
                    temp = 0;
                    left++;
                    right--;
                    k--;
                } else if (temp + prices[left] == split) {
                    temp = 0;
                    left++;
                    k--;
                } else if (temp + prices[right] == split) {
                    temp = 0;
                    right--;
                    k--;
                } else {
                    if (temp + prices[left] < split) {
                        temp = temp + prices[left];
                        left++;
                    } else if (temp + prices[right] > split) {
                        temp = temp + prices[right];
                        right--;
                    } else {
                        return false;
                    }
                }
            }
        }
        return k == 0;
    }

    public static void main(String[] args) {
        给粉丝分礼物 solution = new 给粉丝分礼物();
        // [1,2,2,2,2],3
        int[] prices = {1, 2, 2, 3, 3, 4};
        int k = 3;
        System.out.println(solution.canEqualDistribution(prices, k));
    }
}